import 'package:flutter/material.dart';

class AnimatedSwitcherDemo extends StatefulWidget {
  @override
  _AnimatedSwitcherDemoState createState() => _AnimatedSwitcherDemoState();
}

class _AnimatedSwitcherDemoState extends State<AnimatedSwitcherDemo> {
  int _counter = 0;
  bool _isTextVisible = true;
  Color _currentColor = Colors.blue;
  String _currentText = 'Hello';

  /*生命周期*/
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  @override
  void didUpdateWidget(covariant AnimatedSwitcherDemo oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedSwitcher Demo'),
        backgroundColor: Colors.blue,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 4. 不同尺寸切换动画
            _buildSection(
              '尺寸切换动画',
              '不同大小组件间的过渡效果',
              _buildSizeSwitcher(),
            ),

            // 5. 自定义动画切换
            _buildSection(
              '自定义动画效果',
              '旋转和缩放组合动画',
              _buildCustomAnimation(),
            ),

            // 6. 复杂组件切换
            _buildSection(
              '复杂组件切换',
              '卡片和列表项之间的切换',
              _buildComplexSwitcher(),
            ),
            // 1. 基础数字计数器动画
            _buildSection(
              '基础数字计数器',
              '点击按钮查看数字变化动画',
              _buildBasicCounter(),
            ),

            // 2. 文本显示/隐藏动画
            _buildSection(
              '文本显示/隐藏',
              '淡入淡出动画效果',
              _buildTextVisibility(),
            ),

            // 3. 颜色切换动画
            _buildSection(
              '颜色切换动画',
              '不同颜色间的平滑过渡',
              _buildColorSwitcher(),
            ),


          ],
        ),
      ),
    );
  }

  Widget _buildSection(String title, String description, Widget content) {
    return Card(
      margin: EdgeInsets.only(bottom: 20),
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text(
              description,
              style: TextStyle(color: Colors.grey[600]),
            ),
            SizedBox(height: 16),
            content,
          ],
        ),
      ),
    );
  }

  // 1. 基础数字计数器
  Widget _buildBasicCounter() {
    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 300),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return FadeTransition(opacity: animation, child: child);
          },
          child: Text(
            '$_counter',
            key: ValueKey<int>(_counter),
            style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
          ),
        ),
        SizedBox(height: 16),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _counter--;
                });
              },
              child: Text('减少'),
            ),
            SizedBox(width: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _counter++;
                });
              },
              child: Text('增加'),
            ),
          ],
        ),
      ],
    );
  }

  // 2. 文本显示/隐藏
  Widget _buildTextVisibility() {
    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 500),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return ScaleTransition(scale: animation, child: child);
          },
          child: _isTextVisible
              ? Text(
                  '这段文本会显示和隐藏',
                  key: ValueKey<bool>(_isTextVisible),
                  style: TextStyle(fontSize: 18),
                )
              : SizedBox(key: ValueKey<bool>(_isTextVisible), height: 24),
        ),
        SizedBox(height: 16),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _isTextVisible = !_isTextVisible;
            });
          },
          child: Text(_isTextVisible ? '隐藏文本' : '显示文本'),
        ),
      ],
    );
  }

  // 3. 颜色切换动画
  Widget _buildColorSwitcher() {
    List<Color> colors = [Colors.blue, Colors.red, Colors.green, Colors.orange, Colors.purple];
    List<String> colorNames = ['蓝色', '红色', '绿色', '橙色', '紫色'];

    int colorIndex = colors.indexOf(_currentColor);

    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 600),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return RotationTransition(
              turns: Tween<double>(begin: 0.0, end: 1.0).animate(animation),
              child: child,
            );
          },
          child: Container(
            key: ValueKey<Color>(_currentColor),
            width: 150,
            height: 150,
            decoration: BoxDecoration(
              color: _currentColor,
              borderRadius: BorderRadius.circular(75),
              boxShadow: [
                BoxShadow(
                  color: _currentColor.withOpacity(0.3),
                  blurRadius: 20,
                  spreadRadius: 5,
                )
              ],
            ),
            child: Center(
              child: Text(
                colorNames[colorIndex],
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: 16),
        ElevatedButton(
          onPressed: () {
            setState(() {
              int nextIndex = (colorIndex + 1) % colors.length;
              _currentColor = colors[nextIndex];
            });
          },
          child: Text('切换颜色'),
        ),
      ],
    );
  }

  // 4. 尺寸切换动画
  Widget _buildSizeSwitcher() {
    bool isLarge = _counter % 2 == 0;
    double size = isLarge ? 120 : 60;

    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 400),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return ScaleTransition(scale: animation, child: child);
          },
          child: Container(
            key: ValueKey<double>(size),
            width: size,
            height: size,
            decoration: BoxDecoration(
              color: Colors.teal,
              borderRadius: BorderRadius.circular(size / 2),
            ),
            child: Center(
              child: Text(
                isLarge ? '大' : '小',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: isLarge ? 24 : 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: 16),
        Text('当前尺寸: ${isLarge ? "120x120" : "60x60"}'),
      ],
    );
  }

  // 5. 自定义动画效果
  Widget _buildCustomAnimation() {
    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 800),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return RotationTransition(
              turns: Tween<double>(begin: 0.0, end: 1.0).animate(animation),
              child: ScaleTransition(
                scale: animation,
                child: child,
              ),
            );
          },
          child: Container(
            key: ValueKey<int>(_counter),
            width: 100,
            height: 100,
            decoration: BoxDecoration(
              color: Colors.deepPurple,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Center(
              child: Text(
                '${_counter % 5}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 32,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: 16),
        Text('点击增加按钮查看旋转缩放动画'),
      ],
    );
  }

  // 6. 复杂组件切换
  Widget _buildComplexSwitcher() {
    bool showCard = _counter % 2 == 0;

    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 500),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return SlideTransition(
              position: Tween<Offset>(
                begin: Offset(1.0, 0.0),
                end: Offset.zero,
              ).animate(animation),
              child: child,
            );
          },
          child: showCard
              ? _buildCardWidget()
              : _buildListWidget(),
        ),
        SizedBox(height: 16),
        Text('组件会在卡片和列表项之间切换'),
      ],
    );
  }

  Widget _buildCardWidget() {
    return Card(
      key: ValueKey<String>('card'),
      elevation: 4,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            Icon(Icons.card_giftcard, size: 48, color: Colors.blue),
            SizedBox(height: 12),
            Text(
              '这是一个卡片组件',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text('包含图标和描述文本'),
          ],
        ),
      ),
    );
  }

  Widget _buildListWidget() {
    return Container(
      key: ValueKey<String>('list'),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey),
        borderRadius: BorderRadius.circular(8),
      ),
      child: ListTile(
        leading: Icon(Icons.list, size: 36, color: Colors.green),
        title: Text('列表项组件'),
        subtitle: Text('这是一个列表项，包含图标和文本'),
        trailing: Icon(Icons.arrow_forward),
      ),
    );
  }
}

// 高级 AnimatedSwitcher 示例
class AdvancedAnimatedSwitcherDemo extends StatefulWidget {
  @override
  _AdvancedAnimatedSwitcherDemoState createState() => _AdvancedAnimatedSwitcherDemoState();
}

class _AdvancedAnimatedSwitcherDemoState extends State<AdvancedAnimatedSwitcherDemo> {
  int _currentIndex = 0;
  List<Widget> _pages = [];

  @override
  void initState() {
    super.initState();
    _initializePages();
  }

  void _initializePages() {
    _pages = [
      _buildHomePage(),
      _buildProfilePage(),
      _buildSettingsPage(),
      _buildMessagesPage(),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('高级 AnimatedSwitcher'),
        backgroundColor: Colors.deepPurple,
      ),
      body: Column(
        children: [
          // 动画页面切换
          Expanded(
            child: AnimatedSwitcher(
              duration: Duration(milliseconds: 600),
              transitionBuilder: (Widget child, Animation<double> animation) {
                return SlideTransition(
                  position: Tween<Offset>(
                    begin: Offset(1.0, 0.0),
                    end: Offset.zero,
                  ).animate(animation),
                  child: child,
                );
              },
              child: _pages[_currentIndex],
            ),
          ),

          // 底部导航
          BottomNavigationBar(
            currentIndex: _currentIndex,
            onTap: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
            items: [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: '首页',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.person),
                label: '个人',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.settings),
                label: '设置',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.message),
                label: '消息',
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildHomePage() {
    return Container(
      key: ValueKey<int>(0),
      color: Colors.blue[50],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.home, size: 80, color: Colors.blue),
            SizedBox(height: 20),
            Text(
              '首页',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            Text('欢迎来到首页'),
          ],
        ),
      ),
    );
  }

  Widget _buildProfilePage() {
    return Container(
      key: ValueKey<int>(1),
      color: Colors.green[50],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.person, size: 80, color: Colors.green),
            SizedBox(height: 20),
            Text(
              '个人中心',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            Text('查看个人信息'),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsPage() {
    return Container(
      key: ValueKey<int>(2),
      color: Colors.orange[50],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.settings, size: 80, color: Colors.orange),
            SizedBox(height: 20),
            Text(
              '设置',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            Text('应用设置选项'),
          ],
        ),
      ),
    );
  }

  Widget _buildMessagesPage() {
    return Container(
      key: ValueKey<int>(3),
      color: Colors.purple[50],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.message, size: 80, color: Colors.purple),
            SizedBox(height: 20),
            Text(
              '消息',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            Text('查看消息列表'),
          ],
        ),
      ),
    );
  }
}

// AnimatedSwitcher 与表单示例
class FormAnimatedSwitcherDemo extends StatefulWidget {
  @override
  _FormAnimatedSwitcherDemoState createState() => _FormAnimatedSwitcherDemoState();
}

class _FormAnimatedSwitcherDemoState extends State<FormAnimatedSwitcherDemo> {
  bool _isLogin = true;
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('表单动画切换'),
        backgroundColor: Colors.indigo,
      ),
      body: Padding(
        padding: EdgeInsets.all(24),
        child: AnimatedSwitcher(
          duration: Duration(milliseconds: 400),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return FadeTransition(opacity: animation, child: child);
          },
          child: _isLogin ? _buildLoginForm() : _buildRegisterForm(),
        ),
      ),
    );
  }

  Widget _buildLoginForm() {
    return Container(
      key: ValueKey<bool>(true),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.login, size: 64, color: Colors.indigo),
          SizedBox(height: 30),
          TextField(
            decoration: InputDecoration(
              labelText: '用户名',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.person),
            ),
          ),
          SizedBox(height: 16),
          TextField(
            decoration: InputDecoration(
              labelText: '密码',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.lock),
            ),
            obscureText: true,
          ),
          SizedBox(height: 24),
          SizedBox(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                });
                // 模拟登录过程
                Future.delayed(Duration(seconds: 2), () {
                  setState(() {
                    _isLoading = false;
                  });
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('登录成功')),
                  );
                });
              },
              child: _isLoading
                ? CircularProgressIndicator(color: Colors.white)
                : Text('登录', style: TextStyle(fontSize: 18)),
            ),
          ),
          SizedBox(height: 16),
          TextButton(
            onPressed: () {
              setState(() {
                _isLogin = false;
              });
            },
            child: Text('还没有账户？立即注册'),
          ),
        ],
      ),
    );
  }

  Widget _buildRegisterForm() {
    return Container(
      key: ValueKey<bool>(false),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.app_registration, size: 64, color: Colors.indigo),
          SizedBox(height: 30),
          TextField(
            decoration: InputDecoration(
              labelText: '用户名',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.person),
            ),
          ),
          SizedBox(height: 16),
          TextField(
            decoration: InputDecoration(
              labelText: '邮箱',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.email),
            ),
          ),
          SizedBox(height: 16),
          TextField(
            decoration: InputDecoration(
              labelText: '密码',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.lock),
            ),
            obscureText: true,
          ),
          SizedBox(height: 16),
          TextField(
            decoration: InputDecoration(
              labelText: '确认密码',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.lock),
            ),
            obscureText: true,
          ),
          SizedBox(height: 24),
          SizedBox(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                });
                // 模拟注册过程
                Future.delayed(Duration(seconds: 2), () {
                  setState(() {
                    _isLoading = false;
                  });
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('注册成功')),
                  );
                });
              },
              child: _isLoading
                ? CircularProgressIndicator(color: Colors.white)
                : Text('注册', style: TextStyle(fontSize: 18)),
            ),
          ),
          SizedBox(height: 16),
          TextButton(
            onPressed: () {
              setState(() {
                _isLogin = true;
              });
            },
            child: Text('已有账户？立即登录'),
          ),
        ],
      ),
    );
  }
}

// 主页面 - 展示所有 AnimatedSwitcher 示例
class AnimatedSwitcherMainDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedSwitcher 示例合集'),
        backgroundColor: Colors.blue,
      ),
      body: ListView(
        padding: EdgeInsets.all(16),
        children: [
          _buildDemoCard(
            context,
            '基础 AnimatedSwitcher',
            '展示基本的动画切换效果',
            Icons.animation,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AnimatedSwitcherDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            '高级页面切换',
            '页面间平滑过渡动画',
            Icons.pages,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AdvancedAnimatedSwitcherDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            '表单动画切换',
            '登录注册表单间的动画过渡',
            Icons.app_registration,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => FormAnimatedSwitcherDemo()),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDemoCard(BuildContext context, String title, String description,
      IconData icon, VoidCallback onTap) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 8),
      elevation: 4,
      child: ListTile(
        leading: Icon(icon, size: 40, color: Colors.blue),
        title: Text(
          title,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        subtitle: Text(description),
        trailing: Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }
}

// 使用示例
void main() {
  runApp(MaterialApp(
    title: 'AnimatedSwitcher Demo',
    debugShowCheckedModeBanner: false,
    home: AnimatedSwitcherMainDemo(),
  ));
}
